<template>
  <div class="main">
    <div class="title">
      <div>{{ pageType == 1 ? `Interaction By Virus - Virus: ${abbreviation}` : `Interaction By Virus - Host: ${host}`}}</div>
      <div class="download">
        <div class="btn" @click="downloadClick">
          <span class="titl">Download data</span>
          <i class="el-icon-download"></i>
        </div>
      </div>
    </div>

    <div class="warp" v-if="pageType == 2">
      <div class="sideWarp">
        <div class="tagTitle">Virus abbreviation :</div>
      </div>
      <div class="collapse">
        <div v-loading="abbrLoading" class="tagWarp">
          <div :class="['tag',abbreviation == n.abbreviation ? 'active':'']" v-for="(n, idx) in groupList" :key="idx" @click="searchClick(n)">{{n.abbreviation}}</div>
        </div>
        <el-collapse >
          <el-collapse-item name="1">
            <template slot="title">
              <div class="tips">
                <div>Correspondence between virus abbreviations and full names</div>
              </div>
            </template>

            <div class="abbrWarp">
              <div class="abbrItem" v-for="(n, idx) in groupList" :key="idx">
                <div class="abbrName">{{n.abbreviation}} : </div>
                <div class="content">{{n.list.join(",")}}</div>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>

    <div class="right">
      <div v-loading="loading" id="chartId" style="width: 100%;height: 800px"/>
    </div>


    <el-dialog
        class="dialog"
        :visible="show"
        v-dialogDrag
        :modal="false"
        :close-on-click-modal="false"
        @close="closeHandler"
        width="220px">

      <div slot="title">
        <div>Infomation</div>
      </div>
      <div class="show-information">
        <div class="infoItem" v-for="(n, i) in info.titles" :key="i">
          <span class="item-title">{{info.titles[i]}} : </span>
          <span>{{info.data[i]}}</span>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {exportVirus, exportHost, getHostNodes, getVirusNodes, getVirusGroupsByHost} from "../../api/interaction";
import * as echarts from "echarts";

let myChart = null

export default {
  name: "nodeView",
  components: {},
  data() {
    return {
      abbrLoading: false,
      loading: false,
      abbreviation: null,
      host: null,
      nodeType: null,
      pageType: null,
      // chart: null,
      isHighlight: false,
      clickLastNode: null,
      option: {},
      show: false,
      info: {
        titles: [],
        data: []
      },
      groupList: [],
      isFristInto: true,
    }
  },
  mounted() {
    this.abbreviation = this.$route.query.abbreviation
    this.host = this.$route.query.host
    this.nodeType = this.$route.query.nodeType
    this.pageType = this.$route.query.pageType

    this.initChart()
    this.getVirusData();
  },
  beforeDestroy() {
    myChart.dispose()
  },
  methods: {
    async searchClick(n) {
      myChart.clear()
      this.abbreviation = n.abbreviation
      this.loading = true
      const res = await getHostNodes({
        host: this.host,
        abbreviation: this.abbreviation,
        nodeType: this.nodeType
      })
      this.setOptions(res.data)
      this.loading = false
    },
    async loadVirusGroupsByHost() {
      this.abbrLoading = true
      const res = await getVirusGroupsByHost({host: this.host})

      // 按字母大小排序
      res.data.sort((a,b) => {
        return a.abbreviation.localeCompare(b.abbreviation);
      });

      this.groupList = res.data

      this.abbrLoading = false
      if (this.isFristInto) {
        this.isFristInto = false
        this.searchClick(this.groupList[0])
      }
    },
    closeHandler() {
      this.show = false
    },
    initChart() {
      myChart = echarts.init(document.getElementById('chartId'))
      let fixedTop = 350;

      myChart.off('click') // 很重要！！否则每次渲染都会增加一次点击事件
      myChart.on('click', (params) => {
        // console.log("click  ", params)

        if (params.dataType != "node") {
          return;
        }

        // 获取弹框info信息
        this.show = true

        let rnaType = params.data.type
        let data = params.data.name.split('|')

        if (this.nodeType === 'miranda') {
          if (rnaType.indexOf("mRNA") > -1 ||
              rnaType.indexOf("lncRNA") > -1) {
            // 获取Group
            let group = data[0].split("_")[1]
            this.info.titles = ["Name", "Gene name", "Group"]
            data.push(group)
          }
          else if (rnaType.indexOf("circRNA") > -1) {
            // 获取Group
            let group = data[0].split("_")[1]
            this.info.titles = ['Name', 'Genome', 'Start', 'End', 'Strand', "Group"]
            data.push(group)
          }
          else if (rnaType.indexOf("sRNA") > -1) {
            this.info.titles = ['Name', 'Genome', 'Start', 'End', 'Strand', 'Group']
          }
        }
        else {
          this.info.titles = ['Name', 'Group', 'Gene Symbol']
        }

        this.info.data = data

        // 处理弹框显示位置
        let top = fixedTop - document.documentElement.scrollTop;
        let width = document.documentElement.clientWidth
        let fixedLeft = width / 2.0 - 1170 / 2.0 + 30
        let e = document.getElementsByClassName("el-dialog")[0];
        e.style.top = top + params.event.offsetY + 'px'
        e.style.left = fixedLeft + params.event.offsetX + 'px'
      });

      myChart.on('mouseup', (params) => {
        var option = myChart.getOption();
        // console.log("点击了  ", params)
        if (params.dataType != "node") {
          return;
        }
        option.series[0].data[params.dataIndex].x = params.event.offsetX;
        option.series[0].data[params.dataIndex].y = params.event.offsetY;
        option.series[0].data[params.dataIndex].fixed = true;
        myChart.setOption(option);
      });

      // myChart.on('graphRoam', () => {
      //   this.updatePosition();
      //   this.rememberHighlight( this.clickLastNode);
      // });

      // // 点击空白区域复原
      // myChart.getZr().on('click', (params) => {
      //   console.log('params',params);
      //   if(params.cancelBubble === false && params.target === undefined){
      //     this.updatePosition();
      //     this.isHighlight = false;
      //     this.clickLastNode = null;
      //   }
      // })
    },
    async downloadClick() {
      let data = null

      if (this.pageType == 1) {
        data = await exportVirus({
          abbreviation: this.abbreviation,
          nodeType: this.nodeType
        })
      }else {
        data = await exportHost({
          host: this.host,
          abbreviation: this.abbreviation,
        })
      }

      this.downloadFile(data)
    },
    downloadFile(data) {
      if (!data) {
        return
      }
      let url = window.URL.createObjectURL(new Blob([data]))
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url

      let fileName = (this.pageType == 1 ? (this.abbreviation + "_" + this.nodeType) : this.host) + '.xlsx'
      link.setAttribute('download', fileName)
      document.body.appendChild(link)
      link.click()
    },
    async getVirusData() {
      if (this.pageType == 1) { // 1 virus
        this.loading = true
        const res = await getVirusNodes({
          abbreviation: this.abbreviation,
          nodeType: this.nodeType
        })
        this.setOptions(res.data)
        this.loading = false
      } else {
        // 2 加载 host的病毒分组
        this.loadVirusGroupsByHost()
      }
    },
    setOptions(res) {
      let nodes = []
      let links = [];
      let categ = [];
      let categArr = [];
      let colors = ['rgb(174, 199, 232)', 'rgb(31, 119, 180)', '#6dc3ad'
        , '#fc690f', '#fc2867', '#704dfe', '#f4c099'
      ,'#74c8ef', '#9c1919'];

      nodes = res.nodes
      links = res.links
      categ = res.category

      categArr = []
      if (this.pageType == 1) {
        categ.map((n) => {
          categArr.push({
            name: n,
            icon: 'circle',
          })
        })
      }else {
        categArr = categ
      }

      nodes = nodes.map((item) => {
        item.x = parseInt(Math.random() * 450);
        item.y = parseInt(Math.random() * 450);

        if (this.pageType == 2) {
          item.symbol = item.name.indexOf(this.host) > -1 ? 'circle':'triangle';
          item.symbolSize = 20
        }
        return item;
      })
      let option = {
        color: colors,
        legend: {
          data: categArr
        },
        tooltip: {},
        series: [
          {
            name: this.pageType == 1 ? this.abbreviation : this.host,
            type: 'graph',
            layout: 'force',
            data: nodes,
            links: links,
            categories: categArr,
            roam: true,
            draggable: true,
            label: {
              show: false,
              position: 'right',
              color: 'fff',
            },
            lineStyle: {   // 线的颜色
              normal: {
                color: 'source',
              }
            },
            itemStyle: {
              borderType: 'solid',
              borderColor: '#fff',
              borderWidth: 2
            },
            edgeLabel: {   // 标签的位置，就是线上面的文字
              normal: {
                show: false, // 线条名称
                color: '#000',
                formatter: (e) => {
                  return e.data.name
                },
              },
            },
            edgeSymbol: ['', 'arrow'],
            animation: false,
            animationEasingUpdate: false
          }
        ]
      };

      myChart.setOption(option)
    },

  }
}
</script>

<style lang="stylus" scoped>

.main /deep/ {
  .draggable-box {
    pointer-events: none;
  }

  .el-dialog__wrapper {
    pointer-events: none;

    .el-dialog {
      z-index 9999999;
      pointer-events: auto;
      margin 0!important
    }
  }

  .el-dialog__header {
    background-color: #11427d;
    color: #fff;
    font-size: 14px;
  }

  .el-dialog__headerbtn .el-dialog__close {
    color: #fff;
  }
}

.main {
  width 1170px
  margin-top 20px
  padding-top 10px
  font-family: Times New Roman;

  .infoItem {
    margin-bottom 10px

    .item-title {
      color #11427D
      font-weight 600
      margin-right 5px
    }
  }


  .title {
    font-size 22px
    text-align left
    margin-bottom 20px
    padding 15px 0
    color #11427D
    font-weight 600
    width 100%

    display flex
    justify-content: space-between;
  }

  .collapse /deep/{

    .abbrWarp {
      display flex
      flex-direction column

      .abbrItem {
        display flex
        word-break:break-word;
        margin-bottom 5px
        font-size 15px
        .abbrName {
          font-weight 600
          margin-right 10px
          width 90px
          text-align right
          line-height 1.2
        }
        .content {
          flex 1
          line-height 1.2
        }
      }
    }

    .el-collapse {
      border none
      background-color #f9f9f9
      border-radius 10px
    }
    .el-collapse-item__header {
      border none
      display flex
      align-items center
      background-color #f9f9f9
      border-radius 10px
      padding 0 15px
    }
    .el-collapse-item__wrap {
      border none
      background-color #f9f9f9
      border-bottom-left-radius 10px
      border-bottom-right-radius 10px
      padding 0 30px
    }
    .el-collapse-item__content {


    }
    .el-collapse-item__arrow {
      margin 0
      margin-left 10px
      color rgba(143, 143, 143, 0.7)
      /*display none*/
    }

    .tips {
      color rgba(143, 143, 143, 0.7)
      font-size 16px
      display flex
      flex-direction column
      align-items center
    }
  }

  .warp {
    display flex
    font-family: Times New Roman;
    margin-bottom: 20px;

    .sideWarp {
      padding-left: 20px;
      margin-right 30px
      flex-shrink: 0;
      .tagTitle {
        padding 0
        position: relative;
        font-size 20px
        font-weight 500
        color #0a2458
      }

      .tagTitle::before {
        background-color: #aa604f;
        content: "";
        width: 3px;
        height: 100%;
        position: absolute;
        top: 0;
        left: -20px;
        transition: .2s ease;
      }
    }

    .tagWarp /deep/ {
      display flex
      flex-wrap wrap
      align-items: center;
      width: 100%;

      //设置图标颜色
      .el-loading-spinner .path {
        stroke: #11427D;
      }
      .el-loading-spinner .circular {
        width 25px
        height 25px
      }

      .tag {
        color #989898
        margin-right 20px
        margin-bottom 20px
        font-size 20px
        font-weight 500
        cursor pointer
      }
      .tag:hover, .active {
        color #0a2458
        text-decoration underline
      }
    }
  }

  .download {
    display flex
    justify-content flex-end
    color #3a3a3a

    .btn {
      cursor pointer
    }
    .titl {
      display inset-block
      margin-right 8px
    }
    i {
      padding 8px
      background-color #eaeaea
    }
  }

  .right /deep/ {
    padding-top 30px
    border-radius 6px
    box-shadow: 0 2px 12px 0 rgba(193, 193, 193, 0.39);

    //设置图标颜色
    .el-loading-spinner .path {
      stroke: #11427D;
    }
  }

}
</style>
